import { memo } from 'react';
import type { FC, PropsWithChildren } from 'react';
import { Link } from 'react-router-dom';
import { resCategoryList } from '@/services/category';
import { useRequest } from 'ahooks';

export const renderCategoryItem = (category: API.CategoryListStruct[]) => {
  const categoryItem: API.CategoryListStruct[] = [];
  if (!category) {
    return null;
  }
  for (const c of category) {
    const cs: API.CategoryListStruct[] = [];
    if (!c.children || c.children.length === 0) {
      cs.push(c);
    } else {
      cs.push(...renderCategoryItem(c.children)!);
    }
    categoryItem.push(...cs);
  }
  return categoryItem;
};

const HomeCategory: FC<PropsWithChildren<{}>> = () => {
  const { data, loading } = useRequest(resCategoryList);
  return (
    <div
      className={
        'bg-gray-50 rounded-lg px-4 py-6 font-serif h-full text-center overflow-hidden'
      }
    >
      <div className={'text-lg text-gray-900 mb-3'}>商品分类</div>
      <div className={'grid gap-4 place-content-around grid-cols-2'}>
        {data
          ? renderCategoryItem(data)?.map((value) => (
              <Link
                to={'/search?category_id=' + value.id}
                key={value.id}
                className={'text-gray-600'}
              >
                {value.name}
              </Link>
            ))
          : null}
      </div>
    </div>
  );
};

export default memo(HomeCategory);
